package com.yilin.tms.capital.service.impl;

import com.google.gson.reflect.TypeToken;
import com.yilin.tms.capital.commons.aliPay.AliPayTradeRecord;
import com.yilin.tms.capital.service.ITradeRecordService;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.MapUtil;
import com.yilin.tms.capital.service.IAlipayService;
import com.yilin.tms.core.application.PlatRequest;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayService implements IAlipayService {

    @Resource
    IUserRemote userRemote;
    @Resource
    ITradeRecordService tradeRecordService;
    @Resource
    IOrderRemote orderRemote;

    /**
     * 生成预付单
     * 下单系统
     */
    @Override
    public String tradePaymentOrder(Account loginUser, TradeRecord tradeRecord, String trminalType, String requestFromURl) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        String respont = PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/alipay/tradePaymentOrder", MapUtil.generate(paramMap -> {
            paramMap.put("tradeNo", tradeRecord.getTradeNo());
            paramMap.put("tradeName", tradeRecord.getTransName());
            paramMap.put("outOrganizeId", tradeRecord.getPaymentOrganizeId().replace("（个体）", ""));
            paramMap.put("outAcctName", tradeRecord.getPaymentOrganizeName());
            paramMap.put("inOrganizeId", tradeRecord.getIncomeOrganizeId());
            paramMap.put("inAcctName", tradeRecord.getIncomeOrganizeId().replace("（个体）", ""));
            paramMap.put("tranAmount", tradeRecord.getMoney());
            paramMap.put("remark", tradeRecord.getRemark());
            paramMap.put("trminalType", trminalType);
            paramMap.put("requestFromURl", requestFromURl);
            paramMap.put("userType", loginUser.getUserType());
        }), new TypeToken<String>() {
        });
        ParamUtil.isNull(respont, "支付宝下单平台服务器返回数据为空");
        tradeRecord.setInitiateTime(new Date());
        tradeRecord.setOptUserId(loginUser.getId());
        tradeRecord.setOptUserName(loginUser.getName());
        tradeRecord.setInitiateTime(new Date());
        tradeRecord.setPayType(TradeRecord.PayType.alipay);
        tradeRecord.setBankType(TradeRecord.BankType.none);
        tradeRecordService.saveOrUpdate(tradeRecord);
        return respont;
    }

    /**
     * 支付宝支付：交易结果查询
     * 备注：调这个方法之后需要掉用订单通知接口
     */
    @Override
    public TradeRecord queryAliPayOrder(Account loginUser, TradeRecord tradeRecord) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        AliPayTradeRecord aliPayTradeRecord = PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/alipay/queryAliPayOrder", paramMap, new TypeToken<AliPayTradeRecord>() {
        });
        if (aliPayTradeRecord == null) throw new BusinessException("支付宝查询平台服务器返回数据为空");
        if (tradeRecord.getBankFlowNo() == null) tradeRecord.setBankFlowNo(aliPayTradeRecord.getBankFlowNo());
        if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
            tradeRecord.setFinishTime(aliPayTradeRecord.getCompleteTime());
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        if (aliPayTradeRecord.getBankMsg() != null) tradeRecord.setTradeFailMsg(aliPayTradeRecord.getBankMsg());
        if (tradeRecord.getPaymentCapitalAccount() == null) tradeRecord.setPaymentCapitalAccount(aliPayTradeRecord.getOutAcctNo());
        if (tradeRecord.getIncomeCapitalAccount() == null) tradeRecord.setIncomeCapitalAccount(aliPayTradeRecord.getInAcctNo());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return tradeRecord;
    }

    @Override
    public TradeRecord aliPayRefund(Account loginUser, TradeRecord tradeRecord) {
        tradeRecord.setPayType(TradeRecord.PayType.alipay);
        if (tradeRecord.getOriginalPaymentOrderId() == null) throw new BusinessException("原交易单ID为空");
        TradeRecord originalTradeRecord = tradeRecordService.getTradeRecordById(tradeRecord.getOriginalPaymentOrderId());
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        paramMap.put("tradeName", tradeRecord.getTransName());
        paramMap.put("outOrganizeId", tradeRecord.getPaymentOrganizeId().replace("（个体）", ""));
        paramMap.put("outAcctName", tradeRecord.getPaymentOrganizeName());
        paramMap.put("inOrganizeId", tradeRecord.getIncomeOrganizeId());
        paramMap.put("inAcctName", tradeRecord.getIncomeOrganizeId().replace("（个体）", ""));
        paramMap.put("tranAmount", tradeRecord.getMoney());
        paramMap.put("remark", tradeRecord.getRemark());
        paramMap.put("refundOriginalTradeNo", originalTradeRecord.getTradeNo());
        AliPayTradeRecord aliPayTradeRecord = PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/alipay/aliPayRefund", paramMap, new TypeToken<AliPayTradeRecord>() {
        });
        if (aliPayTradeRecord == null) throw new BusinessException("支付宝查询平台服务器返回数据为空");
        tradeRecord.setInitiateTime(aliPayTradeRecord.getInitiateTime());
        if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        tradeRecord.setBankFlowNo(aliPayTradeRecord.getBankFlowNo());
        if (aliPayTradeRecord.getBankMsg() == null) tradeRecord.setTradeFailMsg(aliPayTradeRecord.getBankMsg());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return tradeRecord;
    }

    @Override
    public TradeRecord aliPayRefundQuery(Account loginUser, TradeRecord tradeRecord ) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        AliPayTradeRecord aliPayTradeRecord = PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/alipay/aliPayRefundQuery", paramMap, new TypeToken<AliPayTradeRecord>() {
        });
        if (aliPayTradeRecord == null) throw new BusinessException("支付宝查询平台服务器返回数据为空");
        if (tradeRecord.getBankFlowNo() == null) tradeRecord.setBankFlowNo(aliPayTradeRecord.getBankFlowNo());
        if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
            tradeRecord.setFinishTime(aliPayTradeRecord.getCompleteTime());
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        } else if (aliPayTradeRecord.getAliPayTradeStatus() == AliPayTradeRecord.AliPayTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        if (aliPayTradeRecord.getBankMsg() != null) tradeRecord.setTradeFailMsg(aliPayTradeRecord.getBankMsg());
        if (tradeRecord.getPaymentCapitalAccount() == null) tradeRecord.setPaymentCapitalAccount(aliPayTradeRecord.getOutAcctNo());
        if (tradeRecord.getIncomeCapitalAccount() == null) tradeRecord.setIncomeCapitalAccount(aliPayTradeRecord.getInAcctNo());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return tradeRecord;
    }

}

